<template>
    <div>
        <ul class="list">
            <li class="item" 
                v-for="item in letters" 
                :key="item" 
                :ref="item" 
                @click="handleLetterClick" 
                @touchstart.prevent="handleTouchStart" 
                @touchmove="handleTouchMove" 
                @touchend="handleTouchEnd"
                >{{item}} 
            </li>
        </ul>    
    </div>
</template>

<script>
export default {
    name:'CityAlphabet',
    // props:{
    //     cities: Object
    // },
    props:['cities'],
    data() {
        return {
            touchStatus: false, //默认touch状态
            startY: 0,
            timer: null
        }
    },
    updated() { 
        this.startY = this.$refs['A'][0].offsetTop; //优化，页面和 data 数据已经更新完毕
    },
    methods: {
        handleLetterClick(e) { //点击右侧字母事件的方法
            // console.log(e.target.innerText);
            this.$emit('change',e.target.innerText);  //给父组件City.vue传值
        },
        handleTouchStart(e) {
            this.touchStatus = true;
        },
        handleTouchMove(e) {
            if(this.touchStatus){
                if(this.timer){  //函数节流，限制一下handleTouchMove函数执行频率
                    clearTimeout(this.timer);
                }
                this.timer = setTimeout( ()=>{ //延迟16毫秒执行
                    // const startY = this.$refs['A'][0].offsetTop; //字母A距离顶部的高度
                    // console.log(startY);
                    const touchY = e.touches[0].clientY - 79; //手指距离顶部的高度（减去顶部的高度）
                    // console.log(touchY);
                    const index = Math.floor((touchY-this.startY)/20); //除以每个字母的高度，得到字母所在位置索引
                    // console.log(index);
                    if(index >= 0 && index < this.letters.length){
                        this.$emit('change',this.letters[index]);
                    }
                },16)
                
            }
        },
        handleTouchEnd() {
            this.touchStatus = false;
        }
    },
    computed: {
        // letters是26个字母组成的一个数组，ref绑定item，使$refs成为26个DOM对象的数组,来把cityes这个对象转换成数组
        letters() {
            const letters = [];
            for(let i in this.cities){
                letters.push(i);
            }
            return letters;  //['A','B','C'...]
        }
    },
}
</script>

<style lang="stylus" scoped>
    @import '~styles/varibles.styl'
    .list
        display: flex
        flex-direction: column
        justify-content: center
        position: absolute
        top: 1.58rem
        right: 0
        bottom: 0
        width: .4rem
        .item
            line-height: .4rem
            text-align: center
            color: $bgColor
</style>